/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.controller;

import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.driving.core.entity.Admin;
import com.driving.core.entity.Coach;
import com.driving.core.entity.Student;
import com.driving.core.service.IAdminService;
import com.driving.core.service.ICoachService;
import com.driving.core.service.IStudentService;
import com.driving.core.util.ConfigReader;
import com.driving.core.util.Constant;
import com.driving.core.util.Constant.Audience;
import com.driving.core.util.JsonWebToken;
import com.driving.core.util.MessageType.ExceptionType;
import com.driving.core.util.Response;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author SAGITTAR
 * @since 2017
 */
@Slf4j
@RestController
@AllArgsConstructor
public class CommonController {

    private final ConfigReader configReader;

    private final IStudentService studentService;

    private final ICoachService coachService;

    private final IAdminService adminService;

    @GetMapping(value = "/validate")
    public Response<Map<String, String>> validate(HttpServletRequest request) {
        String token = request.getHeader(Constant.TOKEN);
        Map<String, String> map = JsonWebToken.validateToken(token);
        if (map.isEmpty()) {
            return Response.failure(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        long id = Long.parseLong(map.remove(Constant.ID));
        String audience = map.remove(Constant.AUDIENCE);
        String password = map.remove(Constant.PASSWORD);
        String name = null;
        // 判断角色，同时判断密码正误
        switch (Audience.from(audience)) {
        case STUDENT:
            Student student = studentService.getById(id);
            if (Objects.nonNull(student) && StringUtils.equals(student.getPassword(), password)) {
                name = student.getNickName();
            }
            break;
        case COACH:
            Coach coach = coachService.getById(id);
            if (Objects.nonNull(coach) && StringUtils.equals(coach.getPassword(), password)) {
                name = coach.getName();
            }
            break;
        case ADMIN:
            Admin admin = adminService.getById(id);
            if (Objects.nonNull(admin) && StringUtils.equals(admin.getPassword(), password)) {
                name = admin.getName();
            }
            break;
        default:
            break;
        }
        // 密码正确
        if (StringUtils.isNotBlank(name)) {
            map.put(Constant.NAME, name);
            return Response.success(map);
        }
        return Response.failure(configReader.getExceptionMessage(ExceptionType.INCORRECT_PASSWORD));
    }
}
